package thread.think;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 手写阻塞队列
 * 思考题 ArrayBlockingQueue利用数组作为队列，那么元素移除的时候如何实现
 *
 * @author ycz
 * @date 2021/7/15
 */
public class WriteBlockingQueue extends QueueBase {


    public WriteBlockingQueue(List<Node> queue, AtomicInteger size, Node head, Node last) {
        super(queue, size, head, last);
    }

    public Boolean add(Object value) {
        Node node = new Node(value);
        headLock.lock();
        if (size.get() == 0) {
            head = last = node;
        } else {
            head = node;
        }
        queue.add(node);
        headLock.unlock();
        return true;
    }

    public Object get() throws InterruptedException {
        Node returnValue = last;
        int queueSize = size.getAndDecrement();
        if (queueSize == 1) {
            // 尾节点 阻塞
            lastCondition.await();
        }
        return returnValue.getValue();
    }




}
